import axios from 'axios'
import qs from 'qs'

axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.withCredentials = true
/**
 * axios 默认 Content-Type: application/json;charset=UTF-8
 * 请求正文为Request Payload，格式是json格式的字符串
 * 台用@RequestParam是接收不到参数的，只能用@RequestBody
 * 配置transformRequest，参数使用qs转换
 * 请求头Content-Type会被设置为: application/x-www-form-urlencoded
 * 请求正文为Form Data，格式是key=value&key1=value2
 * 对于 Form Data 请求，后台无需任何注解，即可解析参数
 */
// axios.defaults.transformRequest = [params => qs.stringify(params)]

// 添加请求拦截器
axios.interceptors.request.use(config => {
  return config
}, error => {
  // 请求错误
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(response => {
  console.log('response 类型:', typeof response);
  console.log('response 内容:', response);
  console.log('response 是 Blob 吗？', response instanceof Blob);
  return response.data
}, error => {
  // 响应错误
  return Promise.reject(error)
})

// 封装GET请求
const oGet = (url, params = {}, config = {}) => {
  return axios.get(url, {
    params,
    ...config
  }).catch(error => {
    console.error('GET请求失败:', error)
    throw error
  })
}

// 封装POST请求 - 支持多种调用方式
const oPost = (urlOrConfig, dataOrSuccessCallback, configOrErrorCallback) => {
  let url, data, successCallback, errorCallback, config = {}

  if (typeof urlOrConfig === 'string') {
    // 旧方式：oPost(url, data, config)
    url = urlOrConfig
    data = dataOrSuccessCallback
    config = configOrErrorCallback || {}
  } else if (urlOrConfig.proxy) {
    // 新方式：oPost({ proxy: { url, datas, responseType, ... } }, success, error)
    url = urlOrConfig.proxy.url
    data = urlOrConfig.proxy.datas || {}
    config = { ...urlOrConfig.proxy } // ✅ 复制所有配置，包括 responseType
    delete config.url
    delete config.datas
    successCallback = dataOrSuccessCallback
    errorCallback = configOrErrorCallback
  }

  return axios({
    method: 'post',
    url,
    data,
    ...config // ✅ 关键：传递 responseType 等配置
  })
    .then(response => {
      if (successCallback && typeof successCallback === 'function') {
        successCallback(response)
      }
      return response
    })
    .catch(error => {
      console.error('POST请求失败:', error)
      if (errorCallback && typeof errorCallback === 'function') {
        errorCallback(error)
      }
      throw error
    })
}

// 导出封装的方法
export { oGet, oPost }
export default axios
